<template>
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item >
        <el-input v-model="searchForm.name" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="getRoleList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addUser">新增</el-button>
      </el-form-item>
      <el-form-item>
        <template>
          <el-popconfirm title="这是一段内容确定删除吗？" @confirm="deleteHandle(null)">
            <el-button slot="reference"  type="danger" :disabled="delBtnStatus">批量删除</el-button>
          </el-popconfirm>
        </template>
      </el-form-item>
    </el-form>

<!--  @selection-change绑定选定框触发事件  -->
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="name"
          label="姓名"
          width="120">
      </el-table-column>
      <el-table-column
          prop="code"
          label="唯一编码"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          prop="remark"
          label="描述"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          prop="statu"
          label="状态"
          show-overflow-tooltip>
<!--        1、获取表单数据，2、判断状态，3、显示不同状态-->
        <template slot-scope="scope">
          <el-tag  size="small" v-if="scope.row.statu === 0" type="success">正常</el-tag>
          <el-tag size="small"  v-else-if="scope.row.statu === 1" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="operation"
          label="操作"
      >
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="permAllocate(scope.row.id)">分配权限</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" size="mini" @click="editHandle(scope.row)">编辑</el-button>
          <!--          垂直分割线-->
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="deleteHandle(scope.row.id)">
              <el-button slot="reference" size="mini" type="text" >删除</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>
    </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    <!--新增角色弹窗-->
    <el-dialog
        title="新增用户"
        :visible.sync="centerDialogVisible"
        width="500px"
        @closed="resetForm('editForm')"
        center>

      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-ruleForm">

        <el-form-item label="角色名称" prop="name" >
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>

        <el-form-item label="唯一编码" prop="code">
          <el-input v-model="editForm.code"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>


        <el-form-item label="状态" prop="statu">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label=0>正常</el-radio>
            <el-radio :label=1>禁用</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item style="margin-left: 60px">
          <el-button type="primary" @click="submitForm('editForm')">提交</el-button>
          <el-button @click="resetForm('editForm')">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
<!--    分配权限弹窗-->
    <el-dialog
        title="权限分配"
        :visible.sync="permDialogVisible"
        width="500px"
        center>
      <el-form :model="permData">
        <el-tree
            :data="permTreeData"
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :default-expand-all="true"
            ref="permTree"
            :props="defaultProps">
        </el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="permDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitPerm()">确定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  name: "Role",
  data(){
    return{
      currentPage: 1,
      total: 30,
      pageSize: 10,
      searchForm: {},

      centerDialogVisible: false,
      permDialogVisible: false,
      editForm:{},
      //分配的权限数据
      permData:{},
      //权限列表
      permTreeData:[],
      //权限树形控件
      defaultProps: {
        //指定子树为节点对象的某个属性值
        children: 'children',
        //指定节点标签为节点对象的某个属性值
        label: 'name'
      },
      editFormRules:{
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输唯一编码', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入描述', trigger: 'blur'}
        ],
        statu: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ]
      },
      delBtnStatus: true,
      tableData: [

      ],
      //使用批量删除时,用于存储勾选数据的整条记录
      //multipleSelection存放勾选记录的所有信息
      multipleSelection: []
    }
  },
  methods: {
    //页面数据条数改变
    handleSizeChange(val) {
      console.log("页面大小改变")
      this.pageSize = val;
      this.getRoleList();
    },
    //当前你所在页码改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getRoleList();
    },
    handleSelectionChange(val){
      this.multipleSelection =  val
      //勾选信息后将批量删除按钮激活
      if(this.multipleSelection.length !== 0){
        this.delBtnStatus = false;
        return
      }
      //取消勾选要将批量删除按钮设为不可选中
      this.delBtnStatus = true;
    },
    //新增用户
    addUser(){
      this.centerDialogVisible  = true;
    },
    //获取用户列表
    getRoleList(){
      this.$axios.get("/sys/role/list",{
        params:{
          name: this.searchForm.name,
          current: this.currentPage,
          size: this.pageSize
        }
      }).then(res => {
        console.log("getRoleList success")
        this.tableData = res.data.data.records;
        this.total = res.data.data.total;
        this.currentPage = res.data.data.current;
        this.pageSize = res.data.data.size;

      })
    },
    //编辑和新增使用的同一提交
    submitForm(formName){
      this.$refs[formName].validate((valid)=>{
        if(valid){
          this.$axios.post('/sys/role/'+(this.editForm.id? "update":"save"),this.editForm).then(res => {
            this.resetForm(formName)
            this.$message({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                this.getMenuTree()
              }
            });
          })
        }else{
          console.log('error submit!!');
          return false;
        }
        this.centerDialogVisible = false;
      })
    },
    //编辑表单项
    editHandle(info){
      this.$axios.get('/sys/role/info/'+info.id).then(res => {
        this.editForm = res.data.data
        this.centerDialogVisible = true
      })
    },
    //删除表单项
    //根据id是否为空判断是否为批量删除
    deleteHandle(id){
      let ids = []
      //删除一条记录
      if(id !==  null){
        ids.push(id)
      }
      else{
        //批量删除
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
      }
      console.log("删除项id")
      console.log(ids)
      this.$axios.post('/sys/role/delete',ids).then(res =>  {
        console.log(res)
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getRoleList()
          }
        });
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.centerDialogVisible = false
    },
    //获取某个角色已经分配的权限
    permAllocate(id){
      this.permDialogVisible = true;
      this.$axios.get('/sys/role/info/'+id).then(res => {
        console.log("info")
        console.log(res)
        this.$refs.permTree.setCheckedKeys(res.data.data.menuIds)
        //返回的结果是SysRole对象
        this.permData = res.data.data
      })
    },
    //分配权限提交
    submitPerm(){
      let menuIds = this.$refs.permTree.getCheckedKeys()
      this.$axios.post('/sys/role/perm/'+this.permData.id,menuIds).then(res => {
        this.$message({
          showClose: true,
          message: "权限分配成功",
          type: "success",
          onClose: () => {this.getRoleList()}
        });
        this.permDialogVisible = false;
      })
    }
  },
  created() {
    this.getRoleList();
  //  页面加载时获取权限列表
    this.$axios.get('/sys/menu/list').then(res => {
      this.permTreeData = res.data.data;
    })
  }
}
</script>

<style scoped>
.el-pagination{
  float: right;
  margin-top: 5px;
}
</style>